package com.cloudcc.mobile.view.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.Toast;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.DownLoadCamCardDao;
import com.cloudcc.mobile.entity.ContactEntity;
import com.cloudcc.mobile.entity.CustomerEntity;
import com.cloudcc.mobile.entity.KeHuMessage;
import com.cloudcc.mobile.entity.LeadEntity;
import com.cloudcc.mobile.entity.Vcard;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.HandleParser;
import com.cloudcc.mobile.parser.KeHuParser;
import com.cloudcc.mobile.parser.ReturnCodeParser;
import com.cloudcc.mobile.parser.VcfFileParser;
import com.cloudcc.mobile.service.HandleService;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.intsig.openapilib.OpenApi;
import com.intsig.openapilib.OpenApiParams;

import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 名片扫描
 * 
 * @author Administrator
 * 
 */
public class CamCardActivity extends BaseActivity {
	private KeHuMessage kmg;
	private int pageSize = 15;
	private int pageNUM = 1;
	private Vcard vv;
	private LeadEntity lead;
	private ContactEntity contact;
	private CustomerEntity kehu;
	private static final int REQUEST_CODE_RECOGNIZE = 0x1001;
	private Context context;
	private String leixing;
	private HandleService service;
	private ProgressDialog dialog;
	public static final int INSERT_CONTACT = 100;
	OpenApi openApi = OpenApi.instance("7y43139YE8TBXB98r17aRLyb");
	OpenApiParams apiParams = new OpenApiParams() {
		{
			this.setRecognizeLanguage("");
			this.setReturnCropImage(true);
			this.setSaveCard(true);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		context = this;
		testRecognizeCapture();
		setUpView();
	}

	@Override
	public int getLayoutId() {
		return R.layout.camcard;
	}

	private void setUpView() {
		leixing = getIntent().getStringExtra("leixing");
		service = new HandleService();
		Intent data = getIntent();
		String trim = data.getStringExtra(OpenApi.EXTRA_KEY_IMAGE);
		dialog = new ProgressDialog(context);

	}

	private void save() {
		lead = new LeadEntity();
		lead.setOwnerid(UserManager.getManager().getUser().userId);
		if (vv.getFn() == null || vv.getFn().equals("null")
				|| vv.getFn().equals("")) {
			handler.sendEmptyMessage(-5);
		} else if (vv.getTellworkfax() == null && vv.getTelcell() == null) {
			handler.sendEmptyMessage(-5);
		} else {
			String name = replaceBlank(vv.getFn());
			if (leixing.equals("lead")) {
				lead.setName(name);// 客户名称
				if (vv.getOrgwork() == null || vv.getOrgwork().equals("null")) {
					int a = vv.getOrgprefwork().indexOf(";");
					if (a > -1) {
						lead.setCompany(vv.getOrgprefwork().substring(0, a));
					} else {
						lead.setCompany(vv.getOrgprefwork());
					}
				} else {
					int a = vv.getOrgwork().indexOf(";");
					if (a > -1) {
						lead.setCompany(vv.getOrgwork().substring(0, a));
					} else {
						lead.setCompany(vv.getOrgwork());
					}
				}
				lead.setEmail(vv.getEmailwork());
				lead.setPhone(vv.getTelcell());
				lead.setDianhua(vv.getTellwork());
				lead.setAddress(vv.getAdrwork());
				lead.setCreatebyid(UserManager.getManager().getUser().userId);
				lead.setWangzhi(vv.getUrlwork());
				lead.setFax(vv.getTellworkfax());
				if (vv.getTitle() == null || vv.getTitle().equals("null")) {
					lead.setZhiwu(vv.getOrgprefwork());
				} else {
					lead.setZhiwu(vv.getTitle());
				}
				final String aa = Json.toJson(lead);
				new Thread() {
					public void run() {
						try {
							String result = service.insertLead(aa);
							if (result.equals("null") || result == null
									|| result.equals("NetworkError")) {
								handler.sendEmptyMessage(-1);
								return;
							} else if (result.equals("outTime")) {
								handler.sendEmptyMessage(-3);
								return;
							}
							String code = ReturnCodeParser
									.getReturnCode(result);
							if (code.equals(-2)) {
								handler.sendEmptyMessage(-2);
								return;
							}
							JSONObject jsonObject = new JSONObject(result);
							boolean isresult = jsonObject.getBoolean("result");
							if (isresult) {
								String id = HandleParser.insertLeadInfo(result);
								if (id != null) {
									handler.sendEmptyMessage(0);
								}
							}
						} catch (Exception e) {
							Tools.handle(e);
						}
					};
				}.start();

			} else if (leixing.equals("account")) {
				contact = new ContactEntity();
				if (vv.getOrgwork() == null || vv.getOrgwork().equals("null")) {
					int xx = vv.getOrgprefwork().indexOf(";");
					if (xx > -1) {
						contact.setKhmcccname(vv.getOrgprefwork().substring(0,
								xx));
					} else {
						contact.setKhmcccname(vv.getOrgprefwork());
					}
				} else {
					int xx = vv.getOrgwork().indexOf(";");
					if (xx > -1) {
						contact.setKhmcccname(vv.getOrgwork().substring(0, xx));
					} else {
						contact.setKhmcccname(vv.getOrgwork());

					}
				}
				contact.setName(name);
				try {
					if (vv.getTitle() == null || vv.getTitle().equals("null")) {
						contact.setZhiwu(vv.getOrgprefwork());
					} else {
						contact.setZhiwu(vv.getTitle());
					}
				} catch (Exception e1) {
					Tools.handle(e1);
					contact.setZhiwu("");
				}
				contact.setEmail(vv.getEmailwork());
				contact.setShouji(vv.getTelcell());
				contact.setDianhua(vv.getTellwork());
				contact.setFax(vv.getTellworkfax());
				// -----------------------------
				kehu = new CustomerEntity();
				if (vv.getOrgwork() == null || vv.getOrgwork().equals("null")) {
					int yy = vv.getOrgprefwork().indexOf(";");
					if (yy > -1) {
						kehu.setName(vv.getOrgprefwork().substring(0, yy));
					} else {
						kehu.setName(vv.getOrgprefwork());
					}
				} else {
					int yy = vv.getOrgwork().indexOf(";");
					if (yy > -1) {
						kehu.setName(vv.getOrgwork().substring(0, yy));
					} else {
						kehu.setName(vv.getOrgwork());
					}
				}
				kehu.setDianhua(vv.getTellwork());
				kehu.setFax(vv.getTellworkfax());
				kehu.setKhdd(vv.getAdrwork());
				kehu.setWangzhi(vv.getUrlwork());
				// 根据客户名称搜索 如果没有这个客户新建客户 新建联系人，如果有客户，
				try {
					String b = "ORDER BY createdate Desc";
					final String expressions = "name like'%" + kehu.getName()
							+ "%' " + b;// 条件
					// 起线程 联网去查
					new Thread() {
						@Override
						public void run() {
							String result = service.getAccount(pageNUM,
									pageSize, expressions);
							if (result == null || result.equals("null")
									|| result.equals("NetworkError")) {
								handler.sendEmptyMessage(-1);
								return;
							} else if (result.equals("outTime")) {
								handler.sendEmptyMessage(-3);
								System.out.println("result=-3");
								return;
							}
							String code = ReturnCodeParser
									.getReturnCode(result);
							if (code.equals(-2)) {
								handler.sendEmptyMessage(-2);
								return;
							}
							kmg = new KeHuMessage();
							kmg = KeHuParser.getKeHu(result);
							if (!kmg.isResult()) {
								handler.sendEmptyMessage(-4);
								return;
							}
							if (kmg.getTotalCount() == 0) {// 没有数据
								final String kh = Json.toJson(kehu);
								new Thread() {
									public void run() {
										try {
											String result = service
													.insertAccount(kh);
											if (result.equals("null")
													|| result == null
													|| result
															.equals("NetworkError")) {
												handler.sendEmptyMessage(-1);
												return;
											} else if (result.equals("outTime")) {
												handler.sendEmptyMessage(-3);
												return;
											}
											String code = ReturnCodeParser
													.getReturnCode(result);
											if (code.equals(-2)) {
												handler.sendEmptyMessage(-2);
												return;
											}
											JSONObject jsonObject = new JSONObject(
													result);
											boolean isresult = jsonObject
													.getBoolean("result");
											if (isresult) {
												String id = HandleParser
														.insertLeadInfo(result);
												if (id != null) {
													contact.setKhmc(id);
													handler.sendEmptyMessage(INSERT_CONTACT);
												}
											}
										} catch (Exception e) {
											Tools.handle(e);
										}
									};
								}.start();
							} else {// 有数据
								contact.setKhmc(kmg.getList().get(0).getId());
								handler.sendEmptyMessage(INSERT_CONTACT);
							}
						}
					}.start();
				} catch (Exception e) {
					Tools.handle(e);
				}

			}
		}

	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				dialog.dismiss();
				Tools.showInfo(CamCardActivity.this, "保存成功");
				CamCardActivity.this.finish();

				break;
			case -1:
				dialog.dismiss();
				Tools.showInfo(CamCardActivity.this, "网络异常,操作失败，请稍后重试");
				CamCardActivity.this.finish();
				break;
			case -2:
				dialog.dismiss();
				Tools.showInfo(CamCardActivity.this, "登陆超时,请重新登录");
				CamCardActivity.this.finish();
				break;
			case -3:
				dialog.dismiss();
				Tools.showInfo(CamCardActivity.this, "网络超时，请稍后重试");
				CamCardActivity.this.finish();
				break;
			case -4:
				dialog.dismiss();
				Tools.showInfo(CamCardActivity.this, "查询失败");
				CamCardActivity.this.finish();
				break;
			case -5:
				dialog.dismiss();
				Tools.showInfo(CamCardActivity.this, "保存失败，名片信息不完整，请重新扫描~");
				CamCardActivity.this.finish();
				break;
			case INSERT_CONTACT:
				new Thread() {
					public void run() {
						try {
							String cc = Json.toJson(contact);
							String rcc = service.insertContact(cc);
							if (rcc.equals("null") || rcc == null
									|| rcc.equals("NetworkError")) {
								handler.sendEmptyMessage(-1);
								return;
							} else if (rcc.equals("outTime")) {
								handler.sendEmptyMessage(-3);
								return;
							}
							String code = ReturnCodeParser.getReturnCode(rcc);
							if (code.equals(-2)) {
								handler.sendEmptyMessage(-2);
								return;
							}
							JSONObject jsonObject = new JSONObject(rcc);
							boolean isresult = jsonObject.getBoolean("result");
							if (isresult) {
								String id = HandleParser.insertLeadInfo(rcc);
								if (id != null) {
									handler.sendEmptyMessage(0);
								}
							}
						} catch (Exception e) {
							Tools.handle(e);
						}

					};
				}.start();
				break;
			}
		}
	};

	private void testRecognizeCapture() {
		
		if (openApi.isCamCardInstalled(this)) {
			// 安装了
			if (openApi.isExistAppSupportOpenApi(this)) {
				openApi.recognizeCardByCapture(this, REQUEST_CODE_RECOGNIZE,
						apiParams);
			} else {
				String msg = "名片全能名片王不是最新版\n 扫描名片需要安装名片全能王最新版，是否开始免费下载?";
				tishi(msg);
			}
		} else {// 没有安装 弹出对话框，提示免费安装
			String msg = "尚未安装名片全能名片王最新版\n 扫描名片需要安装名片全能王最新版，是否开始免费下载?";
			tishi(msg);
		}
	}

	public void testRecognizeImage(String path) {
		if (openApi.isExistAppSupportOpenApi(this)) {
			openApi.recognizeCardByImage(this, path, REQUEST_CODE_RECOGNIZE,
					apiParams);
		} else {
			String msg = "名片全能名片王不是最新版\n 扫描名片需要安装名片全能王最新版，是否开始免费下载?";
			tishi(msg);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		int errorCode = 200;
		if (data != null) {
			errorCode = data.getIntExtra(openApi.ERROR_CODE, 200);
		}
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_CODE_RECOGNIZE) {
				showResult(data.getStringExtra(OpenApi.EXTRA_KEY_VCF),
						data.getStringExtra(OpenApi.EXTRA_KEY_IMAGE));
			}
		} else if (errorCode == 100) {
			Tools.showInfo(context, "device_id错误");
			CamCardActivity.this.finish();
		} else if (errorCode == 101) {
			Tools.showInfo(context, "app_id错误");
			CamCardActivity.this.finish();
		} else if (errorCode == 102) {
			Tools.showInfo(context, "app_key错误");
			CamCardActivity.this.finish();
		} else if (errorCode == 103) {
			Tools.showInfo(context, getString(R.string.mingpianwang_1));
			CamCardActivity.this.finish();
		} else if (errorCode == 104) {
			Tools.showInfo(context, "设备数量超出限制");
			CamCardActivity.this.finish();
		} else if (errorCode == 105) {
			Tools.showInfo(context, "名片张数超出限制");
			CamCardActivity.this.finish();
		} else if (errorCode == 106) {
			Tools.showInfo(context, "User ID错误");
			CamCardActivity.this.finish();
		} else if (errorCode == 300) {
			// Tools.showInfo(context, "用户取消");
			CamCardActivity.this.finish();
		} else if (errorCode == 301) {
			Tools.showInfo(context, "识别失败");
			CamCardActivity.this.finish();
		} else if (errorCode == 501) {
			Tools.showInfo(context, "版本过低");
			new DownLoadCamCardDao().downLoadCamcard(openApi.getDownloadLink(),
					context);
		} else if (errorCode == 511) {
			Tools.showInfo(context, "网络错误");
			CamCardActivity.this.finish();
		} else if (errorCode == 516) {
			Tools.showInfo(context, "签名验证错误");
			CamCardActivity.this.finish();
		} else if (errorCode == 616) {
			Tools.showInfo(context, "无法获取验证信息");
			CamCardActivity.this.finish();
		} else {
			String errorMessage = data.getStringExtra(openApi.ERROR_MESSAGE);
			Toast.makeText(
					this,
					"Recognize canceled/failed. + ErrorCode " + errorCode
							+ " ErrorMsg " + errorMessage, Toast.LENGTH_LONG)
					.show();
		}
	}

	// 赋值
	private void showResult(String vcf, String path) {
		vv = VcfFileParser.parseVcard(vcf);
		dialog.show();
		save();
	}

	/* 提示下载全能名片王 */
	protected void tishi(String msg) {
		DialogUtils dialog = new DialogUtils(context);
		dialog.showCamDialog(context, msg);
		dialog.setOnDoClicktListener(new OnDoClickListener() {
			@Override
			public void confirm() {
				new DownLoadCamCardDao().downLoadCamcard(
						openApi.getDownloadLink(), context);
			}

			@Override
			public void cancel() {
			}
		});
	}

	public String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
}
